package com.tlb.springboot.starter.rocketmq.util;

import java.io.IOException;

import com.aliyun.openservices.ons.api.impl.util.NameAddrUtils;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.common.utils.HttpTinyClient;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 取阿里云地址
 */
@Slf4j
public class AliAddressUtil {
    /**
     * 内网地址
     */
    private static final String WSADDR_INTERNAL = "http://onsaddr-internal.aliyun.com:8080/rocketmq/nsaddr4client-internal";

    /**
     * 外网地址
     */
    private static final String WSADDR_INTERNET = "http://onsaddr-internet.aliyun.com/rocketmq/nsaddr4client-internet";

    private static final long WSADDR_INTERNAL_TIMEOUTMILLS = 3000L;

    private static final long WSADDR_INTERNET_TIMEOUTMILLS = 5000L;

    private static final int OK = 200;

    public static String fetchNSAddr(String nameServer) {
        HttpTinyClient.HttpResult result;
        log.info("nameServer:{}" , nameServer);
        if (StringUtils.isEmpty(nameServer) == false) {
            log.info("use nameServer:{}" , nameServer);
            if (StringUtils.isNotEmpty(nameServer) && NameAddrUtils.NAMESRV_ENDPOINT_PATTERN.matcher(nameServer.trim()).matches()) {
                return nameServer.substring(NameAddrUtils.ENDPOINT_PREFIX.length());
            }

            return nameServer;
        }
        try {
            result = HttpTinyClient.httpGet(WSADDR_INTERNAL, null, null, "UTF-8", WSADDR_INTERNAL_TIMEOUTMILLS);
            log.debug("rocketmq内网地址获取成功");
            if (OK == result.code) {
                if (result.content != null) {
                    return clearNewLine(result.content);
                }
            }
        } catch (IOException e) {
            log.debug("内网地址获取失败");
        }
        try {
            result = HttpTinyClient.httpGet(WSADDR_INTERNET, null, null, "UTF-8", WSADDR_INTERNET_TIMEOUTMILLS);
            log.debug("rocketmq外网地址获取成功");
            if (OK == result.code) {
                if (result.content != null) {
                    return clearNewLine(result.content);
                }
            }
        } catch (IOException e) {
            log.debug("外网地址获取失败");
        }
        throw new RuntimeException("阿里云rocketmq地址获取失败");
    }

    private static String clearNewLine(String str) {
        String newString = str.trim();
        int index = newString.indexOf("\r");
        if (index != -1) {
            return newString.substring(0, index);
        } else {
            index = newString.indexOf("\n");
            return index != -1 ? newString.substring(0, index) : newString;
        }
    }

    public static String getNamespace(String nameServer) {
        String namespace = null;
        if (StringUtils.isNotEmpty(nameServer)) {
            if (NameAddrUtils.validateInstanceEndpoint(nameServer)) {
                namespace = NameAddrUtils.parseInstanceIdFromEndpoint(nameServer);
                log.info("User specify namespace by endpoint: {}.", namespace);
            }
        }
        return namespace;
    }
}
